﻿using System;
using System.Collections.Generic;
using System.Web;
using DevExpress.Xpo;
using System.Web.UI;
using POI.eTransmittal.Enitity;
using DevExpress.Web.ASPxUploadControl;
using DevExpress.Web;
using DevExpress.Data.Filtering;
using POI.eTransmittal.BusinessRule;
using System.IO;

namespace POI.eTransmittal.WebApp
{
    public class BasePage : System.Web.UI.Page,IAuditProvider
    {
        public UnitOfWork CurrentUnitOfWork;
        public BasePage()
        {
            CurrentUnitOfWork = new UnitOfWork();
           
        }
        
        private void initializeEventHandler()
        {
            if (this.Master != null)
            {
                DevExpress.Web.ASPxNavBar.ASPxNavBar navBarMenu = (DevExpress.Web.ASPxNavBar.ASPxNavBar)this.Master.FindControl("NavBarMenu");

                navBarMenu.ItemDataBound += new DevExpress.Web.ASPxNavBar.NavBarItemEventHandler(NavBarMenu_ItemDataBound);
            }
        }
     
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (Session["UserId"] == null || !string.IsNullOrEmpty(Request.QueryString["uid"]))
            InitializeLogon();
          initializeEventHandler();
       
        }

        protected  virtual void  ShowFlashMessage(){

        }
        public virtual void ShowErrMessage()
        {

        }
        protected virtual  void SetFlashMessage(string message)
        {
            Session["POI.eTransmittal.flashmessage"] = message;
        }
        protected virtual void ClearFlashMessage()
        {
            Session.Remove("POI.eTransmittal.flashmessage");
        }
        protected string GetFlashMessage()
        {
            return Session["POI.eTransmittal.flashmessage"] == null ? "" : Session["POI.eTransmittal.flashmessage"].ToString();
        }
        protected virtual void SetErrorMessage(string message)
        {
            Session["POI.eTransmittal.errmessage"] = message;
        }
        protected string  GetErrorMessage()
        {
            return Session["POI.eTransmittal.errmessage"] == null ? "" : Session["POI.eTransmittal.errmessage"].ToString();
        }
        protected void ClearErrmessage()
        {
            Session.Remove("POI.eTransmittal.errmessage");
        }
        protected override void OnLoadComplete(EventArgs e)
        {
            if (Master != null)
            {
                if (base.Page.Title != "")
                    Master.Page.Title = base.Page.Title + " - eTransmittal - Premier Oil Indonesia";
                else
                    Master.Page.Title = "eTransmittal - Premier Oil Indonesia";
              
                    (this.Master as eTransmittal).UpdateLoginInfo(CurrUserId, CurrentUserRole != null ? CurrentUserRole.RoleName : "Unregistered");

                
            }
        }
        protected string CurrUserId
        {
            get { return (Session["UserId"] != null) ? Session["UserId"].ToString() : string.Empty; }
         //   get { return "jamaludin"; }
        }
        protected Role CurrentUserRole
        {
            get
            {
                User curUser = CurrentUnitOfWork.FindObject<User>(CriteriaOperator.Parse("UserID=?", CurrUserId));
                if (curUser != null)
                    return curUser.Role;
                return null;
            }
        }
        private void InitializeLogon()
        {
            try
            {
                string errMsg = String.Empty;
                string ntUserId = String.Empty;

                System.Security.Principal.IPrincipal principal = HttpContext.Current.User;
                string[] identityName = principal.Identity.Name.Split('\\');
                if (identityName.Length > 1)
                {
                    ntUserId = identityName[1];
                }
                else
                {
                    ntUserId = principal.Identity.Name;
                }


                if (!string.IsNullOrEmpty(Request.QueryString["uid"]))
                    ntUserId = Request.QueryString["uid"];

                //UserInfo info = GetUserInfo(ntUserId);


                Session["UserId"] = null;
                Session["Role"] = null;
                //Session["UserName"] = null;

                Response.Cache.SetNoStore();

                Session["UserId"] = ntUserId;

                //ETransmittalUser user = _unitOfWork.FindObject<ETransmittalUser>(CriteriaOperator.Parse("LOWER(UserId)=?", ntUserId.ToLower()));

                //if (user == null)
                //{
                //    Session["Role"] = UNREGISTERED_ROLE;
                //}
                //else
                //{
                //    Session["Role"] = user.RoleProfile.Code;
                //    user.LastLogonDate = DateTime.Now;
                //    user.Save();
                //    _unitOfWork.CommitChanges();
                //}

            }
            catch (Exception exc)
            {
                if (exc.Message != String.Empty)
                {
                    //ShowErrMessage(exc.Message);
                    //if (this.Master != null)
                    //{
                    //    ASPxRoundPanel pnl = (ASPxRoundPanel)this.Master.FindControl("ASPxRoundPanel1");
                    //    ContentPlaceHolder ph = (ContentPlaceHolder)pnl.FindControl("ContentPlaceHolder1");
                    //    ph.Visible = false;
                    //}
                }
            }
        }

        private void NavBarMenu_ItemDataBound(object sender, DevExpress.Web.ASPxNavBar.NavBarItemEventArgs e)
        {
            User curUser = CurrentUnitOfWork.FindObject<User>(CriteriaOperator.Parse("UserID=?", CurrUserId));
            if (curUser != null)
            {
                Role curUserRole = curUser.Role;

                bool enabled = true;
                if (e.Item.NavigateUrl == "Profile.aspx")
                {
                    enabled = curUserRole.AccessRights.Contains(AccessRights.MANAGE_USER_PROFILE);
                }
                else if (e.Item.NavigateUrl == "ParameterSetup.aspx")
                {
                    enabled = curUserRole.AccessRights.Contains(AccessRights.MANAGE_SYSTEM_SETTINGS);
                }
                else if (e.Item.NavigateUrl == "javascript:GotoNewIncoming()")
                {
                    enabled = curUserRole.AccessRights.Contains(AccessRights.MODIFY_OWNED_INCOMING_TRANSMITTAL);
                }
                else if (e.Item.NavigateUrl == "javascript:GotoNewOutgoing()")
                {
                    enabled = curUserRole.AccessRights.Contains(AccessRights.MODIFY_OWNED_OUTGOING_TRANSMITTAL);
                }
                else if (e.Item.NavigateUrl == "~/InquiryIncoming.aspx")
                {
                    enabled = curUserRole.AccessRights.Contains(AccessRights.VIEW_INCOMING_TRANSMITTAL);
                }
                else if (e.Item.NavigateUrl == "~/InquiryOutgoing.aspx")
                {
                    enabled = curUserRole.AccessRights.Contains(AccessRights.VIEW_OUTGOING_TRANSMITTAL);
                }

                e.Item.Enabled = enabled;
                e.Item.ClientEnabled = enabled;
            }
        }

        protected void RegisterXpodatasource(params  XpoDataSource[] xpods){
            foreach(XpoDataSource xpod in xpods)
            xpod.Session = CurrentUnitOfWork;
    }

        #region IAuditProvider Members

        string IAuditProvider.CurrUserId
        {
            get { return CurrUserId; }
        }

        #endregion
    }
 public   class TempFile
    {
        const string sessionKey = "poi.transmittal.tempFile";
        public UploadedFile File;
        const string sessionTempFilesDelete = "poi.transmittal.delete";
        public string TempFile_UNC_Link
        {
            get
            {
                if (!string.IsNullOrEmpty(TempFileLoc))
                {
                    string uncPath = TempFileLoc.Replace("\\", "/");
                    return "file://" + uncPath;
                }
                return "";
            }
        }
        public string TempFileLoc;
        public TempFile(UploadedFile file)
        {
            File = file;
        }
        public TempFile()
        {
        }
        public static TempFile GetFileFromSession(Page page)
        {
            return (TempFile)page.Session[sessionKey];
        }
        public static void StoreTempFile(Page page, UploadedFile fileToUpload)
        {
            TempFile tf = new TempFile(fileToUpload);
            page.Session[sessionKey] = tf;
        }
        public static void StoreToTempFolder(BasePage basepage, UploadedFile fileToUpload)
        {
            string tempPath = CommonBusinessRules.GetTempShareFolder(basepage.CurrentUnitOfWork);
            string tempFileName = Guid.NewGuid().ToString();
         string tempFull=   Path.Combine(tempPath, tempFileName + Path.GetExtension(fileToUpload.FileName));
         fileToUpload.SaveAs(tempFull);
         TempFile tf = new TempFile(fileToUpload);
         tf.TempFileLoc = tempFull;
         basepage.Session[sessionKey] = tf;
        }
        public  static void Clear(Page page)
        {
            TempFile tm = GetFileFromSession(page);
            if (tm != null)
            {
                if (!string.IsNullOrEmpty(tm.TempFileLoc))
                {
                    List<string> files = page.Session[sessionTempFilesDelete] != null ? (List<string>)page.Session[sessionTempFilesDelete] : new List<string>();
                    files.Add(tm.TempFileLoc);
                    page.Session[sessionTempFilesDelete] = files;
                   
                }
            }
            page.Session.Remove(sessionKey);
           
        }
        public static void DeleteTempfiles(Page page)
        {
            List<string> files = page.Session[sessionTempFilesDelete] != null ? (List<string>)page.Session[sessionTempFilesDelete] : new List<string>();
            FileInfo fi;
            try
            {
                foreach (string f in files)
                {
                    fi = new FileInfo(f);
                    if (fi.Exists)
                    {
                        fi.Delete();
                    }
                }
            }
            catch
            {
            }
        }
    }
}